﻿/*
 * GeneicSeriallize
 * Author: Nguyen Van Truong
 * 
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Xml.Serialization;
using System.IO;
using log4net;

namespace DataDesign.MPP.Utilities
{
    #region Serialize and DeSerialize
    public class GenericSerialize<T>
    {
        private static log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public static string Serialize(T t)
        {
            return Serialize(t, null, null);
        }

        public static string Serialize(T t, string strPrefix, string strNamespace)
        {
            logger.Info("Begin : static string Serialize(T t)");

            string strReturn = "";
            try
            {
                StringWriter sw = new StringWriter();
                XmlSerializerNamespaces namespaceManager = new XmlSerializerNamespaces();
                XmlSerializer ser;

                if (!string.IsNullOrEmpty(strNamespace))
                {
                    namespaceManager.Add(strPrefix, strNamespace);
                    ser = new XmlSerializer(typeof(T), strNamespace);
                    ser.Serialize(sw, t, namespaceManager);
                }
                else
                {
                    ser = new XmlSerializer(typeof(T));
                    ser.Serialize(sw, t);
                }

                strReturn = sw.ToString();
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                //throw ex;
            }

            logger.Info("End : static string Serialize(T t)");

            return strReturn;
        }

        public static T DeSerialize(string s, string strNamespace)
        {
            logger.Info("Begin : static T DeSerialize(string s)");

            T t = default(T);

            try
            {
                StringReader sr = new StringReader(s);
                XmlSerializer ser;
                if (!string.IsNullOrEmpty(strNamespace))
                {
                    ser = new XmlSerializer(typeof(T), strNamespace);
                }
                else
                {
                    ser = new XmlSerializer(typeof(T));
                }

                t = (T)ser.Deserialize(sr);
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                throw ex;
            }

            logger.Info("End : static T DeSerialize(string s)");

            return t;
        }

    }

    #endregion Serialize and DeSerialize
}
